from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import requests
import os
import undetected_chromedriver.v2 as uc
from selenium.webdriver.chrome.options import Options
import requests

def getdrvier(self) :
        driver=None
        chrome_options = webdriver.ChromeOptions()
        user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        chrome_options.add_argument(f'--user-agent={user_agent}')
        chrome_options.add_argument('--ignore-certificate-errors')
        chrome_options.add_argument('--ignore-ssl-errors')
        chrome_options.add_argument('--disable-extensions')  # 禁用扩展
        chrome_options.add_argument('--disable-software-rasterizer')  # 禁用软件光栅化
# 添加常规选项
        chrome_options.add_argument('--disable-logging')  # 禁用日志
        chrome_options.add_argument('--log-level=3')  # 仅显示严重错误
        chrome_options.add_argument('--silent')  # 静默模式
        
        # 禁用开发者工具相关的警告
        chrome_options.add_experimental_option('excludeSwitches', [
            'enable-logging',
            'enable-automation'
        ])
        
        # 设置首选项
        prefs = {
            'devtools.preferences.currentDockState': '"undocked"',  # 开发者工具设置
            'devtools.timeline.hidden-categories': '["*"]',  # 隐藏所有类别
            'profile.default_content_setting_values.notifications': 2,  # 禁用通知
            'profile.default_content_settings.popups': 0  # 禁用弹窗
        }
        chrome_options.add_experimental_option('prefs', prefs)
        chrome_options.add_argument('--window-size=1920,1080')
        chrome_options.add_argument('--start-maximized')  # 最大化窗口
        chrome_options.add_argument('--force-device-scale-factor=1')  # 设置缩放比例为1
        chrome_options.add_argument('--high-dpi-support=1')  # 支持高DPI
        user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
        chrome_options.add_argument(f"user-agent={user_agent}")


# Set the custom headers

        # 禁用缩放
        chrome_options.add_argument('--disable-gpu')
        chrome_options.add_argument('--disable-software-rasterizer')
        current_path=os.getcwd()
        chromedriver_path = os.path.join(current_path, "chromedriver.exe")
        # 创建 Service 对象并传入路径
        
        service = Service(executable_path=chromedriver_path)
        # 创建 WebDriver 实例时传入 Service 对象和 ChromeOptions
        driver = webdriver.Chrome(service=service, options=chrome_options)

        
        return driver   # driver.maximize_window()

def get_headers_from_selenium():
    # Set up Chrome options
     
    driver = getdrvier()

    try:
        # Navigate to the Walmart page
        driver.get('https://www.walmart.ca')

        # Access requests made by the browser
        for request in driver.requests:
            if request.response:
                print(f"Request URL: {request.url}")
                print(f"Request Headers: {request.headers}")
                print(f"Response Headers: {request.response.headers}")
                return request.headers  # Return the headers of the first request
    finally:
        driver.quit()

def make_request_with_captured_headers(item_id):
    headers = get_headers_from_selenium()

    # Example cookies, replace with actual cookies if needed
    cookies = {
        'example_cookie_name': 'example_cookie_value'
    }

    json_data = {
        'query': 'query ItemByIdBtf( $p13nCls:JSON $tempo:JSON $fetchP13N:Boolean! $fMrkDscrp:Boolean! $pageType:String! $fIdml:Boolean! $iId:String! $fSId:Boolean! $eSb:Boolean! $enableDetailedBeacon:Boolean! $enableClickTrackingURL:Boolean! $eCc:Boolean! $fIdmlOrMrkDscrp:Boolean! $enableMultiSave:Boolean = false $tenant:String! = "WM_GLASS" $enableRxDrugScheduleModal:Boolean = false $enablePromoData:Boolean = false ){idml(itemId:$iId html:true) @include(if:$fIdmlOrMrkDscrp){...IDMLFragment @include(if:$fIdml)...MarketingDescriptionFragment @include(if:$fMrkDscrp)}contentLayout( channel:"WWW" pageType:$pageType tenant:$tenant version:"v1" ){modules(p13n:$p13nCls tempo:$tempo){configs{__typename...on EnricherModuleConfigsV1 @include(if:$fetchP13N){zoneV1}...CompleteTheLookModule...on TempoWM_GLASSWWWItemCarouselConfigsV1 @include(if:$fetchP13N){products{...ContentLayoutProduct athAsset}enableEnhancedTile subTitle showGridView isExternalTrafficOverlayCarousel isAtfSectionItemCarousel title minItems type athModule itemsSelection spBeaconInfo{adUuid moduleInfo pageViewUUID placement max}viewAllLink{linkText title clickThrough{type value rawValue tag}uid}}...on TempoWM_GLASSWWWInteractiveImageCarouselConfigsV1 @include(if:$fetchP13N){type items title subTitle isInteractiveImageCarousel isAtfSectionItemCarousel interactiveImageCarouselSpan:span athModule firstTile key products{...ContentLayoutProduct}viewAllLink{linkText title clickThrough{type value rawValue tag}uid}spBeaconInfo{adUuid moduleInfo pageViewUUID placement max}interactiveImageCarouselTileOptions:tileOptions{productTitle}}...on TempoWM_GLASSWWWItemComparisonChartConfigsV1 @include(if:$eCc){compChartItems:products{...comparisonChartItems}tileOptions{...tileOptionsV1}athModule title}...on TempoWM_GLASSWWWSoftBundlesConfigs @include(if:$eSb){products{...ContentLayoutProduct}subTitle sTitle:title collapse __typename athModule}...on TempoWM_GLASSWWWCompressedItemCarouselConfigs{title subTitle manualShelfId isAtfSectionItemCarousel similarItems:products{athAsset...ContentLayoutProduct}type athModule spBeaconInfo{adUuid moduleInfo pageViewUUID placement max}}...on TempoWM_GLASSWWWTabbedCarouselConfigs{title subTitle athModule itemCarousel{tabName tabId tileOptions{productTitle productPrice displayStandardPrice displayWasPrice displayAveragePriceCondition displayPricePerUnit fulfillmentBadging averageRatings mediaRatings productFlags productLabels addToCart addToRegistry addToList displayVariant addToCartButtonStyle}products{...ContentLayoutProduct}spBeaconInfo{adUuid moduleInfo pageViewUUID placement max}}}}moduleId matchedTrigger{pageType pageId zone inheritable}name type version status publishedDate}pageMetadata{p13nMetadata}}}fragment PreorderFragment on PreOrder{isPreOrder releaseDate}fragment MarketingDescriptionFragment on Idml{marketingDescription{name value}}fragment ProductPriceFragment on ProductPrice{price priceString variantPriceString currencyUnit bestValue}fragment CompleteTheLookModule on TempoWM_GLASSWWWItemCompleteTheLookConfigsV1{title subTitle athModule products{...CompleteTheLookProduct}p13nCtlColumn1{...CompleteTheLookColumn}p13nCtlColumn2{...CompleteTheLookColumn}p13nCtlColumn3{...CompleteTheLookColumn}looks{...CompleteTheLookMultipleLooks}}fragment CompleteTheLookProduct on Product{name brand catalogSellerId canonicalUrl availabilityStatus externalInfo{url}id imageInfo{thumbnailUrl id name}priceInfo{currentPrice{...ProductPriceCTLModuleFragment}wasPrice{...ProductPriceCTLModuleFragment}}badges{flags{__typename}}usItemId}fragment ProductPriceCTLModuleFragment on ProductPrice{price priceString variantPriceString currencyUnit bestValue}fragment CompleteTheLookColumn on TempoWM_GLASSWWWP13nCtlColumn{isAnchor cellSpan index isLong}fragment CompleteTheLookMultipleLooks on TempoWM_GLASSWWWP13nCtlMultipleLooks{p13nCtlColumn1{...CompleteTheLookColumn}p13nCtlColumn2{...CompleteTheLookColumn}p13nCtlColumn3{...CompleteTheLookColumn}}fragment BadgesFragment on UnifiedBadge{flags{__typename...on BaseBadge{id text key rank query type styleId @include(if:$fSId) bundleId @include(if:$enableMultiSave)}...on PreviouslyPurchasedBadge{id text key lastBoughtOn styleId criteria{name value}}}labels{__typename...on BaseBadge{id text key}...on PreviouslyPurchasedBadge{id text key lastBoughtOn styleId}}tags{__typename...on BaseBadge{id text key type}}...BadgeGroupFragment}fragment BadgeGroupFragment on UnifiedBadge{groups{__typename name members{...on BadgeGroupMember{__typename id key memberType rank slaText styleId text type iconId badgeContent{__typename id type usecase value styleId}}...on CompositeGroupMember{__typename join memberType styleId suffix members{__typename id key memberType rank slaText styleId text type iconId badgeContent{__typename id type usecase value}}}}}...GenericBadgeFragment}fragment ContentLayoutProduct on Product{id name athAsset badges{...BadgesFragment}clickTrackingURL @include(if:$enableClickTrackingURL) canonicalUrl classType availabilityStatus showAtc personalizable isReplenishable externalInfo{url}averageRating socialInfo{socialHandleName}fulfillmentBadge fulfillmentSpeed fulfillmentTitle fulfillmentType annualEvent annualEventV2 earlyAccessEvent isEarlyAccessItem eventAttributes{priceFlip specialBuy}itemType groupMetaData{groupType groupSubType numberOfComponents groupComponents{quantity offerId componentType productDisplayName}}imageInfo{thumbnailUrl id name width height imageMaps{configs{shape coords{x y}anchorPoint metadataConfigs{...on ItemImageMapMetaData{itemId type name price}}}}}productType numberOfReviews offerId orderMinLimit orderLimit weightIncrement p13nDataV1{predictedQuantity flags{PREVIOUSLY_PURCHASED{text}CUSTOMERS_PICK{text}}}previouslyPurchased{label}preOrder{...PreorderFragment}priceInfo{currentPrice{...ProductPriceFragment priceDisplay}listPrice{...ProductPriceFragment}subscriptionPrice{priceString}shipPrice{...ProductPriceFragment}priceDisplayCodes{clearance eligibleForAssociateDiscount finalCostByWeight priceDisplayCondition reducedPrice rollback submapType}priceRange{minPrice maxPrice priceString}unitPrice{...ProductPriceFragment}wasPrice{...ProductPriceFragment}comparisonPrice{...ProductPriceFragment}savingsAmount{priceString}capType walmartFundedAmount{...ProductPriceFragment}wPlusEarlyAccessPrice{memberPrice{...ProductPriceFragment priceDisplay}savings{amount priceString}eventStartTime eventStartTimeDisplay}}promoDiscount{discount discountEligible discountEligibleVariantPresent promotionId promoOffer state type showOtherEligibleItemsCTA min awardValue}rhPath rxDrugScheduleType @include(if:$enableRxDrugScheduleModal) brand @include(if:$enableDetailedBeacon) category{path @include(if:$enableDetailedBeacon){name url}categoryPath categoryPathId}type salesUnit sellerId sellerName sellerType hasSellerBadge seller{name sellerId}shippingOption{slaTier shipMethod}quickShop quickShopCTALabel showOptions snapEligible promoData @include(if:$enablePromoData){type templateData{priceString imageUrl}}sponsoredProduct{spQs clickBeacon viewBeacon spTags}usItemId variantCount variantCriteria{name id variantList{name swatchImageUrl selectedProduct{usItemId canonicalUrl}}}}fragment IDMLFragment on Idml{arExperience{name values}genAiDetails{genAiDescription}sizeCharts{id tagDisplay url}chokingHazards{...LegalContentFragment}productHighlights{name value iconURL}directions{name value}indications{name value}ingredients{activeIngredientName{name value}activeIngredients{name value}inactiveIngredients{name value}ingredients{name value}}longDescription shortDescription interactiveProductVideo specifications{name value}drugGuide{name value}warnings{name value}warranty{information length url}esrbRating mpaaRating nutritionFacts{calorieInfo{...NutritionAttributeFragment}keyNutrients{name values{...NutritionAttributeFragment}}vitaminMinerals{...NutritionAttributeFragment}servingInfo{...ServingAttributeFragment}additionalDisclaimer{...IdmlAttributeFragment values{...IdmlAttributeFragment values{...IdmlAttributeFragment}}}staticContent{...IdmlAttributeFragment values{...IdmlAttributeFragment values{...IdmlAttributeFragment}}}}videos{poster title versions{small large}}product360ImageContainer{name url}hasMarketingDescription}fragment NutritionAttributeFragment on NutritionAttribute{name mainNutrient{...NutrientFragment}childNutrients{...NutrientFragment childNutrients{...NutrientFragment}}}fragment NutrientFragment on Nutrient{name amount dvp childNutrients{name amount dvp}}fragment ServingAttributeFragment on ServingAttribute{name values{...IdmlAttributeFragment values{...IdmlAttributeFragment}}}fragment IdmlAttributeFragment on IdmlAttribute{name value attribute}fragment LegalContentFragment on LegalContent{ageRestriction headline headline image mature message}fragment tileOptionsV1 on CLSTempoWM_GLASSMobileCommonTileOptions{addToCart averageRatings displayAveragePriceCondition displayPricePerUnit displayStandardPrice displayWasPrice fulfillmentBadging mediaRatings productFlags productLabels productPrice productTitle}fragment comparisonChartItems on Product{availabilityStatus averageRating brand canonicalUrl catalogSellerId classType fulfillmentType fulfillmentBadge id imageInfo{thumbnailUrl}name externalInfo{url}numberOfReviews orderLimit showOptions showAtc category{categoryPath categoryPathId}offerId priceInfo{priceDisplayCodes{finalCostByWeight submapType priceDisplayCondition}currentPrice{...ProductPriceFragment priceDisplay}wasPrice{...ProductPriceFragment}comparisonPrice{priceString}unitPrice{...ProductPriceFragment}savings{priceString}savingsAmount{priceString}shipPrice{...ProductPriceFragment}subscriptionPrice{price priceString intervalFrequency duration percentageRate subscriptionString}priceRange{minPrice maxPrice priceString currencyUnit denominations{price priceString selected}}listPrice{...ProductPriceFragment}capType walmartFundedAmount{...ProductPriceFragment}wPlusEarlyAccessPrice{memberPrice{...ProductPriceFragment priceDisplay}savings{amount priceString}eventStartTime eventStartTimeDisplay}}sellerId sellerName shippingOption{shipMethod}usItemId comparisonChart{...ComparisonChartFragment}}fragment ComparisonChartFragment on ComparisonChart{usItemId title sections{sectionName attributes{attrId displayName dataType highlight value}}}fragment GenericBadgeFragment on UnifiedBadge{groupsV2{name flow pos members{memType memId memStyleId fbMemStyleId content{type value styleId fbStyleId contDesc url actionId}}}}',
        'variables': {
            'isMobile': False,
            'layout': [
                'itemDesktop',
            ],
            'channel': 'WWW',
            'version': 'v1',
            'p13nCls': {
                'pageId': item_id,
                'availabilityStatus': 'IN_STOCK',
                'p13NCallType': 'BTF',
                'p13nMetadata': '',
                'lazyModules': [],
            },
            'fetchP13N': True,
            'fMrkDscrp': False,
            'pageType': 'ItemPageGlobal',
            'fIdml': False,
            'fRev': False,
            'iId': item_id,
            'bbe': False,
            'fSId': True,
            'eSb': True,
            'enableDetailedBeacon': False,
            'enableMultiSave': True,
            'enableClickTrackingURL': True,
            'eCc': False,
            'fIdmlOrMrkDscrp': False,
            'tenant': 'CA_GLASS',
            'epsv': True,
            'enableRxDrugScheduleModal': True,
        },
    }

    response = requests.post(
        f'https://www.walmart.ca/orchestra/graphql/ip/{item_id}',
        cookies=cookies,
        headers=headers,
        json=json_data,
    )

    return response

# Example usage
item_id = '7IWAKQ3KK8OY'
response = make_request_with_captured_headers(item_id)
print(f"Response for item {item_id}: {response.status_code}")
print(response.json())  # Print the JSON response